/****************************************************
 * Description: 后台管理员首页
 * Copyright:   Copyright (c) 2013
 * Company:     beiwaionline
 * @author      caoxl
 * @version     1.0
 * @see
	HISTORY
	*  2013-07-23 caoxl Create File
**************************************************/
package com.bfsuol.common.controller;

import com.bfsuol.common.service.LoginService;
import com.bfsuolcomponents.log.BfsuolLogger;
import com.bfsuolframework.core.BfsuolConstants;
import com.bfsuolframework.core.controller.LoginInfo;
import com.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuolframework.core.controller.support.DefaultQueryParam;
import com.bfsuolframework.core.controller.support.QueryParam;
import com.bfsuolframework.core.exception.ValidationException;
import com.bfsuolframework.core.utils.EncryptUtils;
import com.bfsuolframework.core.utils.StringUtils;
import com.bfsuolframework.security.PrivilegeService;
import com.bfsuolframework.security.SecurityContext;
import com.bfsuolframework.security.entity.BaseUser;
import com.bfsuolframework.security.entity.Menu;
import com.bfsuolframework.security.entity.dto.Privilege;
import com.bfsuolframework.security.service.BaseUserService;
import com.bfsuolframework.security.service.MenuService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

	/**
	 * 后台管理员的首页
	 * @author caoxl
	 */
	@Controller
	@RequestMapping("/index")
	public class IndexController  extends SpringControllerSupport {

	protected final Logger logger = Logger.getLogger(getClass());
	@Autowired
    private MenuService menuService;
	@Autowired
    private BaseUserService baseUserService;
	@Autowired
	private LoginService loginService;

	/**
	 * 加载后台首页
	 * @param model
	 * @return
	 */
	@RequestMapping("/managerIndex")
	public String managerIndex(HttpServletRequest request,Model model){
		// logininfo
		LoginInfo loginInfo = (LoginInfo) getRequest().getSession().getAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);
		model.addAttribute("loginInfo", loginInfo);
		
		// headmenu
		List<Menu> menus = menuService.findAll(new DefaultQueryParam().addQuery("parentId!nu@l", "").addOrderAsc("orderSn").addOrderAsc("id"));//所有的根节点(root节点)
		model.addAttribute("headmenus", menus);
		
		// treemenustr
		String menuDataString=this.menuList(request, menus);
		model.addAttribute("menuData", menuDataString);
		
		return "/common/index/admin";
	}
	
	/**
	 * 加载学员端首页
	 * @param model
	 * @return
	 */
	@RequestMapping("/learnerIndex")
	public String learnerIndex(Model model){
		LoginInfo loginInfo = (LoginInfo) getRequest().getSession().getAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);
		if(loginInfo!=null){
			BaseUser baseUser = loginService.getById(loginInfo.getUserId());
			if(null != baseUser) {
				model.addAttribute("baseUser", baseUser);
				
			}
		}
		model.addAttribute("loginInfo", loginInfo);
		
		return "/common/index/learner";
	}
	
	
	/**
	 * 显示所有菜单
	 * @return
	 */
	public   String menuList(HttpServletRequest request, List<Menu> menus){
		StringBuffer sb = new StringBuffer();
		String content = request.getContextPath();
		String[] roleCodes  = this.getLoginInfo().getRoleCodes();
		QueryParam query = new DefaultQueryParam();
		List<Menu> allMenus=menuService.findAll(query.addOrderAsc("orderSn").addOrderAsc("id"));
		sb.append("[");
		sb = this.listChildren(menus,allMenus,sb,content,roleCodes);
		sb.append("]");
		String jsonString=sb.toString();
		if(jsonString.contains(",]")||jsonString.contains(",}")){
			jsonString=jsonString.replace(",]", "]").replace(",}", "}");
		}
		System.out.println(jsonString);
		return jsonString;
	}
	/**
	 * 遍历所有子节点
	 * @param menus 所有根节点
	 * @param sb StringBuffer
	 * @return 拼接的json字符串
	 */
	private StringBuffer listChildren(List<Menu> menus,List<Menu> allMenus,StringBuffer sb,String content,String[] roleCodes){
		Menu menu = null;
		LoginInfo loginInfo=this.getLoginInfo();
		for(int j=0;j<menus.size();j++){
			menu =menus.get(j);
			if(!"admin".equals(loginInfo.getLoginName())&&!SecurityContext.hasMenu(menu,roleCodes)){
				continue;
			}
			sb.append("{");
			sb.append("\"id\":\""+menu.getId()+"\",");
			if(this.hasSubMenu(menu,allMenus)){
				sb.append("\"state\":\""+"opened"+"\",");
			}else{
				sb.append("\"state\":\""+"open"+"\",");
			}
			sb.append("\"text\":\""+menu.getTitle()+"\",");
			if(!this.hasSubMenu(menu,allMenus)&&menu.getUrl()!=null){
				sb.append("\"href\":\""+content+menu.getUrl()+"\",");
			}
			//List<Menu> childs = menuService.findAll(new DefaultQueryParam().addQuery("parentId!eq@l", menu.getId()).addOrderAsc("id"));
			List<Menu> childs =new ArrayList<Menu>();
			for(int i=0;i<allMenus.size();i++){
				if(allMenus.get(i).getParentId()!=null&&allMenus.get(i).getParentId().equals(menu.getId())){
					childs.add(allMenus.get(i));
				}
			}
			if( null != childs && childs.size() > 0){
				sb.append("\"nodes\":");
				sb.append("[");
				this.listChildren(childs,allMenus ,sb,content,roleCodes);//递归调用
				sb.append("]");
			}
			if(j<menus.size()-1)
				sb.append("},");
			else{
				sb.append("}");
			}
		}
		return sb;
	}
	private boolean hasSubMenu(Menu menu,List<Menu> allMenus) {
		//QueryParam query = new DefaultQueryParam();
		List<Menu> childs =new ArrayList<Menu>();
		for(int i=0;i<allMenus.size();i++){
			if(allMenus.get(i).getParentId()!=null&&allMenus.get(i).getParentId().equals(menu.getId())){
				childs.add(allMenus.get(i));
			}
		}
		if(childs.size()>0){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 显示所有可以作为父菜单的菜单
	 * @return
	 */
	@RequestMapping("/menuChildList")
	public  @ResponseBody String menuChildList(){
		StringBuffer sb = new StringBuffer();
		QueryParam query = new DefaultQueryParam();
		List<Menu> menus = menuService.findAll(query.addQuery("parentId!nu@l", "").addOrderAsc("orderSn").addOrderAsc("id"));//所有的根节点(root节点)
		sb.append("[");
		sb = this.listCanBeParent(null,menus,sb);
		sb.append("]");
		String str = null;
		if(sb.length() > 2)
			str = "{\"id\":\"\",\"text\":\"一级菜单\"},";
		else
			str = "{\"id\":\"\",\"text\":\"一级菜单\"}";
		sb.insert(1, str);
		return sb.toString();
	}
	
	/**
	 * 显示除自己和自己节点的所有可以作为父菜单的菜单
	 * @param id 排除的菜单id
	 * @return
	 */
	@RequestMapping("/menuChildList/{id}")
	public  @ResponseBody String menuChildListId(@PathVariable("id") Long id){
		StringBuffer sb = new StringBuffer();
		QueryParam query = new DefaultQueryParam();
		Menu menu = menuService.getById(id);
		List<Menu> menus = menuService.findAll(query.addQuery("parentId!nu@l", "").addOrderAsc("orderSn").addOrderAsc("id"));//所有的根节点(root节点)
		sb.append("[");
		sb = this.listCanBeParent(menu,menus,sb);
		sb.append("]");
		String str = null;
		if(sb.length() > 2)
			str = "{\"id\":\"\",\"text\":\"一级菜单\"},";
		else
			str = "{\"id\":\"\",\"text\":\"一级菜单\"}";
		sb.insert(1, str);
		return sb.toString();
	}

	/**
	 * 遍历可以作为父菜单的子节点
	 * @param id 自己的id
	 * @param menus	所有根节点
	 * @param sb
	 * @return
	 */
	private StringBuffer listCanBeParent(Menu m,List<Menu> menus,StringBuffer sb){
		Menu menu = null;
		for(Iterator<Menu> it = menus.iterator();it.hasNext();){
			menu = it.next();
			if(null != m && menu.getId().longValue() == m.getId().longValue()){//当遍历menu等于被选中要修改的menu，跳出此次循环
				int index = sb.lastIndexOf(",");
				if(index == sb.length()-1 && !it.hasNext())
					sb.deleteCharAt(index);
				continue;
			}
			sb.append("{");
			sb.append("\"id\":\""+menu.getId()+"\",");
			sb.append("\"text\":\""+menu.getTitle()+"\",");
			//找当前节点的所有子节点
			List<Menu> childs = menuService.findAll(new DefaultQueryParam().addQuery("parentId!eq@l", menu.getId()).addOrderAsc("orderSn").addOrderAsc("id"));
			if( null != childs && childs.size() > 0){
				sb.append("\"nodes\":");
				sb.append("[");
				this.listCanBeParent(m,childs, sb);//递归调用
				sb.append("]");
			}
			if(it.hasNext())
				sb.append("},");
			else
				sb.append("}");
		}
		return sb;
	}
	/**
	 * 通过权限code得到相对应的title
	 * @param code
	 * @return
	 */
	private String getPrivilegeTitle(String code){
		Privilege p = PrivilegeService.getPrivilege(code);
		if(null == p)
			return "";
		else
			return p.getTitle();
	}
	
	/**
	 * 通过权限code得到相应的URL
	 * @param code
	 * @return
	 */
	private String getPrivilegeURL(String code){
		Privilege p = PrivilegeService.getPrivilege(code);
		if(null == p)
			return "";
		else
			return p.getUrl();
	}
	/**
	 * 进入用户密码修改的页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/modifyPwdPre")
	public   String modifyPwdPre(Model model){
		return "/common/index/passwordModify";
	}
	/**
	 * 进入用户基本信息修改的页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/personalInfoPre")
	public   String personalInfoPre(Model model){
		LoginInfo loginInfo = this.getLoginInfo();
    	BaseUser baseUser = baseUserService.getById(loginInfo.getUserId());
    	model.addAttribute("baseUser", baseUser);
		return "/common/index/personalInfo";
	}
	/**
	 * 密码修改
	 * @param oldpassword
	 * @param newpassword
	 * @param session
	 * @return
	 */
	 @RequestMapping("/passwordModify")
	  public @ResponseBody MessageJson passwordModify(@RequestParam("oldpassword") String oldpassword,
													  @RequestParam("newpassword") String newpassword,HttpSession session){
	    	if(StringUtils.isBlank(oldpassword)) return MessageJson.error("修改失败,请输入原密码!");
	    	if(StringUtils.isBlank(newpassword)) return MessageJson.error("修改失败,请输入新密码!");
	    	LoginInfo loginInfo = this.getLoginInfo();
	    	BaseUser loginUser = baseUserService.getById(loginInfo.getUserId());
	    	if(!loginUser.getPassword().equals(EncryptUtils.MD5Encode(oldpassword))){
	    		return MessageJson.error("修改失败,您输入的原密码不正确!");
	    	}else{
		    	loginUser.setPassword(EncryptUtils.MD5Encode(newpassword));
		    	baseUserService.update(loginUser);
				BfsuolLogger.data("密码修改，用户名：",this.getLoginInfo().getUserName());	
	    		return MessageJson.information("密码修改成功!");
	    	}
	   	}
	 /**
	  * 登录用户基本信息修改
	  * @param baseUser
	  * @return
	  */
	 @RequestMapping("/personalInfoModify")
	  public @ResponseBody MessageJson personalInfoModify(@ModelAttribute BaseUser baseUser){
		 BaseUser _baseUser = new BaseUser();
		_baseUser = baseUserService.getById(baseUser.getId());
		String email = baseUser.getEmail();
		if(!StringUtils.isBlank(email) && !email.equals(_baseUser.getEmail())){
			/*boolean yes = baseUserService.isPropertyUnique("email",email, null);
			if (!yes) {
				throw new ValidationException(("邮箱已存在"));
			}*/
		}
		String mobile = baseUser.getMobile();
		if(!StringUtils.isBlank(mobile) &&!mobile.equals(_baseUser.getMobile())){
			/*boolean yes = baseUserService.isPropertyUnique("mobile",mobile, null);
			if (!yes) {
				throw new ValidationException(("手机已存在"));
			}*/
		}
		_baseUser.setUserName(baseUser.getUserName());
		_baseUser.setUserNameEn(baseUser.getUserNameEn());
		_baseUser.setNickname(baseUser.getNickname());
		_baseUser.setGender(baseUser.getGender());
		_baseUser.setBirthday(baseUser.getBirthday());
		_baseUser.setHomePhone(baseUser.getHomePhone());
		_baseUser.setMobile(baseUser.getMobile());
		_baseUser.setMsn(baseUser.getMsn());
		_baseUser.setQq(baseUser.getQq());
		_baseUser.setEmail(baseUser.getEmail());
		_baseUser.setAddress(baseUser.getAddress());
		_baseUser.setPostcode(baseUser.getPostcode());
		baseUserService.update(_baseUser);
		BfsuolLogger.data("修改基本信息，用户名：",this.getLoginInfo().getUserName());
		return MessageJson.success("保存成功");
	 }

		public static void main(String[] args) {
			//CAS 浅拷贝与深拷贝
			//JVM 对象是否存活 数据库索引是如何分类
			//explain 索引为什么会快
			//groupby having
			//linux 命令 source top
			//boot 多套执行环境


			//
		}
}
